package com.cy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 服务消费方对象的启动类
 * 业务描述：
 * 当客户端（浏览器，手机APP）向服务消费方发起请求时，
 * 服务消费方调用服务提供方的api，进而获取服务提供方的数据
 * 例如：
 * 我们访问一个订单模块*/
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
    @Bean
    public RestTemplate restTemplate(){
        System.out.println("==resTemplate()==");
        return new RestTemplate();
    }
    @RestController
    public class ConsumerController{
        /**负载均衡客户端对象*/
        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @Autowired
        private RestTemplate restTemplate;
        @Value("${spring.application.name}")
        private String appName;
        @GetMapping("/consumer/doRestEcho1")
        public String doRestEcho1(){
            String url=
                    "http://localhost:8081/provider/echo/"+appName;
            return restTemplate
                    .getForObject(url,
                            String.class);
        }
        @GetMapping("/consumer/doRestEcho2")
        public String doRestEcho2(){
            ServiceInstance instance =
                    loadBalancerClient
                    .choose("sca-provider");
            String ip = instance.getHost();
            int port=instance.getPort();
//            String url="http://"+ip+":"+port+"/provider/echo/"+appName;
           String url=String.format(
                   "http://%s:%s/provider/echo/%s",ip,port,appName);
            return restTemplate.getForObject(
                    url,
                    String.class);
        }
    }
    /**负载均衡方式调用*/

}

